//
//  TJMessageController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJMessageController.h"
#import "HJChatMessageTextCell.h"
#import "HJChatMessageVideoCell.h"
#import "HJChatMessageVoiceCell.h"
#import "HJChatMessageFileCell.h"
#import "HJChatMessageImageCell.h"
#import "HJChatMessageSystemCell.h"
#import "HJChatMessageNoticeCell.h"
#import "HJChatMessageTransferCell.h"
#import "HJChatMessageUnknowCell.h"

#import "HJChatMessageModel.h"
#import "HJIM.h"
#import "TUIDefine.h"
#import "NSString+emoji.h"
#import "HJPopMenuController.h"
#import "HJChatMessageLayoutHeader.h"
#import "HJFlutterController.h"
#import "HJUIAlertController.h"
#import <SafariServices/SafariServices.h>
#import "HJDownloadManager.h"

#define MaxDateMessageDelay 300

@interface HJMessageController ()<HJChatMessageCellDelegate, SFSafariViewControllerDelegate>

@property (nonatomic, assign) NSInteger pageNumber;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) BOOL isLoadAllMessage;

@property (nonatomic, strong) HJChatMessageModel *msgForDateModel;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) NSDictionary *menuDatas;
@property (nonatomic, strong) NSMutableDictionary *userInfoPool;

@end

@implementation HJMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNumber = 1;
    self.pageSize = 20;
    IQKeyboardManager.sharedManager.enable = NO;
    [self setUpTableView];
    [self loadMessageData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUserInfoChangeNotification:) name:userInfoChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleReceiveOfflineMessageNotification:) name:receiveOfflineMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInserMessageNotification:) name:inserMessageNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLoadLinkInfoCompleteNotification:) name:loadLinkInfoCompleteNotification object:nil];
    
}

- (void)setUpTableView {
    
    self.tableView.backgroundColor = UIColor.tj_F6F6F6Color;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollsToTop = NO;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerClass:HJChatMessageTextCell.class forCellReuseIdentifier:@"HJChatMessageTextCell"];
    [self.tableView registerClass:HJChatMessageVideoCell.class forCellReuseIdentifier:@"HJChatMessageVideoCell"];
    [self.tableView registerClass:HJChatMessageVoiceCell.class forCellReuseIdentifier:@"HJChatMessageVoiceCell"];
    [self.tableView registerClass:HJChatMessageFileCell.class forCellReuseIdentifier:@"HJChatMessageFileCell"];
    [self.tableView registerClass:HJChatMessageImageCell.class forCellReuseIdentifier:@"HJChatMessageImageCell"];
    [self.tableView registerClass:HJChatMessageSystemCell.class forCellReuseIdentifier:@"HJChatMessageSystemCell"];
    [self.tableView registerClass:HJChatMessageNoticeCell.class forCellReuseIdentifier:@"HJChatMessageNoticeCell"];
    [self.tableView registerClass:HJChatMessageTransferCell.class forCellReuseIdentifier:@"HJChatMessageTransferCell"];
    [self.tableView registerClass:HJChatMessageUnknowCell.class forCellReuseIdentifier:@"HJChatMessageUnknowCell"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapViewController)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, TMessageController_Header_Height)];
    headerView.backgroundColor = UIColor.redColor;
    self.indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, TMessageController_Header_Height)];
    self.indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    self.tableView.tableHeaderView = self.indicatorView;
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 10, 0)];
    [self.indicatorView startAnimating];
}

- (void)handleReceiveOfflineMessageNotification:(NSNotification *)not {
    NSDictionary *dict = not.object;
    
    HJChatSessionModel *sessionModel = dict[@"sessionModel"];
    
    if (![sessionModel.sessionId isEqualToString:self.sessionModel.sessionId]) return;
    
    NSArray *messages = dict[@"messages"];
    [HJIM.shareIM.conversationManager readMessageWithSessionId:sessionModel.sessionId msgIds:nil completion:nil];
    
    //根据时间在内存中消息进行排序
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    NSArray *itemsSortedArray = [messages sortedArrayUsingDescriptors:@[sortDescriptor]];
    
    NSMutableArray *messageLayouts = [NSMutableArray array];
    
    //计算布局
    self.msgForDateModel = nil;
    for (NSInteger i = itemsSortedArray.count - 1; i >= 0; i--) {
        
        HJChatMessageModel *messageModel = itemsSortedArray[i];
        HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
        messageLayout.isShowTime = [self isShowTimeWithMessageModel:messageModel];
        [messageLayout calculateLayout];
        [messageLayouts addObject:messageLayout];
    }
    
    dispatch_async_main_queue(^{
        [self.messageLayouts addObjectsFromArray:messageLayouts];
        [self.tableView reloadData];
        [self.tableView layoutIfNeeded];
        [self scrollToBottom:NO];
    });
}

- (void)handleUserInfoChangeNotification:(NSNotification *)not {
    id object = not.object;
    
    dispatch_async_sql_queue(^{
        
        HJChatUserModel *userModel = object;
        if (![object isKindOfClass:HJChatUserModel.class]) {
            userModel = [HJIM.shareIM.userManager queryUserInfoByUserId:object];
        }
        
        if (!userModel.userId) {
            return;
        }
        
        [self.userInfoPool setObject:userModel forKey:userModel.userId];
        
        for (HJChatMessageLayout *obj in self.messageLayouts) {
            
            if ([userModel.userId isEqualToString:obj.messageModel.senderId]) {
                obj.messageModel.senderNickname = userModel.showName;
                obj.messageModel.senderAvatar = userModel.avatar;
                CGFloat nameW = [obj.messageModel.senderNickname getStringSizeWithWidth:KScreenWidth - 140 fontSize:12].width;
                CGRect nameLabelRect = obj.nameLabelRect;
                nameLabelRect.size.width = nameW;
                obj.nameLabelRect = nameLabelRect;
            }
        }
        
        dispatch_async_main_queue(^{
            [self.tableView reloadData];
        });
    });
    
}

- (void)didTapViewController {
    if(self.delegate && [self.delegate respondsToSelector:@selector(didTapInMessageController:)]) {
        [self.delegate didTapInMessageController:self];
    }
}

- (NSMutableArray<HJChatMessageLayout *> *)messageLayouts {
    if (!_messageLayouts) {
        _messageLayouts = [NSMutableArray array];
    }
    return _messageLayouts;
}

- (void)scrollToBottom:(BOOL)animated {
    NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
    if (totalRow == 0 || self.messageLayouts.count == 0) return;
    if (totalRow == self.messageLayouts.count) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageLayouts.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    } else {
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageLayouts.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageLayouts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJChatMessageLayout *messageLayout = self.messageLayouts[indexPath.row];
    
    HJChatMessageCell *cell = nil;
    if ([messageLayout isKindOfClass:HJChatMessageSystemLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageSystemCell" forIndexPath:indexPath];
        cell.messageLayout = messageLayout;
        return cell;
    }
    
    if ([messageLayout isKindOfClass:HJChatMessageTextLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageTextCell" forIndexPath:indexPath];
    } else if ([messageLayout isKindOfClass:HJChatMessageImageLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageImageCell" forIndexPath:indexPath];
    }  else if ([messageLayout isKindOfClass:HJChatMessageVideoLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageVideoCell" forIndexPath:indexPath];
    } else if ([messageLayout isKindOfClass:HJChatMessageVoiceLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageVoiceCell" forIndexPath:indexPath];
    } else if ([messageLayout isKindOfClass:HJChatMessageNoticeLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageNoticeCell" forIndexPath:indexPath];
    } else if ([messageLayout isKindOfClass:HJChatMessageTransferLayout.class]) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageTransferCell" forIndexPath:indexPath];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HJChatMessageUnknowCell" forIndexPath:indexPath];
    }
    
    if ([cell isKindOfClass:HJChatMessageCell.class]) {
        cell.delegate = self;
    }
    cell.messageLayout = messageLayout;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.messageLayouts[indexPath.row].cellHeight;
}

- (void)updateMessage:(HJChatMessageModel *)messageModel {
    dispatch_safe_queue(^{
        
        NSInteger index = -1;
        
        for (NSInteger i = self.messageLayouts.count - 1; i >= 0; i--) {
            HJChatMessageLayout *obj = self.messageLayouts[i];
            if ([obj.messageModel.sessionId isEqualToString:messageModel.sessionId]) {
                if ([obj.messageModel.msgId isEqualToString:messageModel.msgId]) {
                    obj.messageModel.msgStatus = messageModel.msgStatus;
                    obj.messageModel.orderStatus = messageModel.orderStatus;
                    index = i;
                    break;
                }
            }
        }
        
        if (index < 0)  {
            return;
        }
        
        HJChatMessageLayout *targetMessageLayout = self.messageLayouts[index];
        HJChatMessageModel *messageModel = targetMessageLayout.messageModel;
        
        if (messageModel.msgStatus == HJMessageStatusSending) {
            NSLog(@"全局刷新");
            [self.tableView reloadData];
            return;
        }
        
        if (messageModel.isRetry) {
            [self.tableView reloadData];
        } else {
            @try {
                NSLog(@"刷新消息 %ld", index);
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            } @catch (NSException *exception) {
                [self.tableView reloadData];
            } @finally {}
        }
    });
    
}

- (void)handleInserMessageNotification:(NSNotification *)not {
    HJChatMessageModel *messageModel = not.object;
    if (messageModel && [messageModel.sessionId isEqualToString:self.sessionModel.sessionId]) {
        HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
        [self addNewMessage:messageLayout];
    }
}

- (void)handleLoadLinkInfoCompleteNotification:(NSNotification *)not {
    
    NSDictionary *notData = not.object;
    HJChatMessageModel *messageModel = notData[@"message"];
    NSString *parsedUrl = notData[@"url"];
    
    if (messageModel && [messageModel.sessionId isEqualToString:self.sessionModel.sessionId]) {
        
        NSInteger index = -1;
        
        for (NSInteger i = self.messageLayouts.count - 1; i >= 0; i--) {
            HJChatMessageLayout *obj = self.messageLayouts[i];
            if ([obj.messageModel.sessionId isEqualToString:messageModel.sessionId]) {
                if ([obj.messageModel.msgId isEqualToString:messageModel.msgId]) {
                    obj.messageModel.linkPreviewInfo = messageModel.linkPreviewInfo;
                    index = i;
                    break;
                }
            }
        }
        
        if (index < 0)  {
            return;
        }
        
        NSMutableArray *reloadRowsAtIndexPaths = [NSMutableArray array];
        HJChatMessageLayout *messageLayout = self.messageLayouts[index];
        [messageLayout calculateLayout];

        NSMutableArray *reloadMessageLayouts = [NSMutableArray array];
        [reloadMessageLayouts addObject:messageLayout];
        
        BOOL isContainLastObject = NO;
        for (HJChatMessageCell *cell in self.tableView.visibleCells) {
            if ([cell.messageLayout isKindOfClass:HJChatMessageTextLayout.class]) {
                HJChatMessageTextLayout *textLayout = (HJChatMessageTextLayout *)cell.messageLayout;
                if (textLayout.links.count) {
                    NSString *url = textLayout.links.firstObject;
                    if ([url isEqualToString:parsedUrl]) {
                        textLayout.messageModel.linkPreviewInfo = messageModel.linkPreviewInfo;
                        [textLayout calculateLayout];
                        [textLayout.messageModel bg_saveOrUpdateAsync:nil];
                        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
                        [reloadRowsAtIndexPaths addObject:indexPath];
                        [reloadMessageLayouts addObject:textLayout];
                    }
                }
            }
        };
        
        @try {
            [UIView setAnimationsEnabled:NO];
            [self.tableView reloadRowsAtIndexPaths:reloadRowsAtIndexPaths withRowAnimation:UITableViewRowAnimationNone];
            [UIView setAnimationsEnabled:YES];

            for (HJChatMessageTextLayout *textLayout in reloadMessageLayouts) {
                if (textLayout == self.messageLayouts.lastObject) {
                    [self scrollToBottom:YES];
                    break;
                }
            }
        } @catch (NSException *exception) {
            [self.tableView reloadData];
        } @finally {
            
        }
    }
}

- (HJChatMessageLayout *)getLastShowTimeLayout {
    for (NSInteger i = self.messageLayouts.count - 1; i >= 0; i--) {
        HJChatMessageLayout *messageLayout = self.messageLayouts[i];
        if (messageLayout.isShowTime) {
            return messageLayout;
        }
    }
    return nil;
}

- (HJChatMessageLayout *)getFirstShowTimeLayout {
    for (NSInteger i = 0; i < self.messageLayouts.count; i++) {
        HJChatMessageLayout *messageLayout = self.messageLayouts[i];
        if (messageLayout.isShowTime) {
            return messageLayout;
        }
    }
    return nil;
}

- (void)addNewMessage:(HJChatMessageLayout *)messageLayout {
    
    dispatch_safe_queue(^{
        
        self.msgForDateModel  = [self getLastShowTimeLayout].messageModel;
        messageLayout.isShowTime = [self isShowTimeWithMessageModel:messageLayout.messageModel];
        [messageLayout calculateLayout];
        [self.messageLayouts addObject:messageLayout];
        
        if (messageLayout.messageModel.isRetry) {
            [self.tableView reloadData];
            [self scrollToBottom:NO];
            return;
        }
 
        @try {
            [UIView setAnimationsEnabled:NO];
            [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.messageLayouts.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            [UIView setAnimationsEnabled:YES];
        } @catch (NSException *exception) {
            [self.tableView reloadData];
        } @finally {
            
        }
 
        dispatch_async_main_queue(^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                [self scrollToBottom:YES];
            });
        });
        
        if (messageLayout.messageModel.userInfoChange) {
            [self.userInfoPool removeObjectForKey:messageLayout.messageModel.senderId];
            [[NSNotificationCenter defaultCenter] postNotificationName:userInfoChangeNotification object:messageLayout.messageModel.senderId];
        }
    });
}

- (void)chatMessageCell:(HJChatMessageCell *)cell longGesture:(HJChatCellLongTapType)longTapType {
    if (longTapType == HJChatCellLongTapTypeAvatar) {
        if ([self.delegate respondsToSelector:@selector(messageController:onLongSelectMessageAvatar:)]) {
            [self.delegate messageController:self onLongSelectMessageAvatar:cell];
        }
        return;
    }
    
    if (longTapType == HJChatCellLongTapTypeContentView) {
        
        NSMutableArray *types = [NSMutableArray array];
        if (cell.messageLayout.messageModel.messageType == HJMessageTypeText || cell.messageLayout.messageModel.messageType == HJMessageTypeNotice) {
            [types addObject:@(HJPopMenuTypeCopy)];
        }
        
        [types addObject:@(HJPopMenuTypeDelete)];
        
        HJPopMenuController *popMenuController = [[HJPopMenuController alloc] initWithTypes:types];
        TJWeakify(self)
        popMenuController.controllerName = NSStringFromClass(self.class);
        popMenuController.sourceRect = [cell convertRect:cell.containerView.frame toView:getMainWindow()];
        [popMenuController showInController:self];
        [popMenuController setDidSelectItemBlock:^(HJPopMenuType type) {
            if (type == HJPopMenuTypeCopy) {
                NSString *text = cell.messageLayout.messageModel.content;
                [HJTools copyStringToPasteboard:text];
                return;
            }
            
            if (type == HJPopMenuTypeDelete) {
                [weakself deleteMessage:cell.messageLayout];
                return;
            }
        }];
        return;
    }
}

- (void)chatMessageCell:(HJChatMessageCell *)cell tapGesture:(HJChatCellClickType)clickType {
    if (clickType == HJChatCellClickTypeAvatar) {
        if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageAvatar:)]) {
            [self.delegate messageController:self onSelectMessageAvatar:cell];
        }
    } else {
        if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageContent:)]) {
            [self.delegate messageController:self onSelectMessageContent:cell];
        }
    }
    
}

- (void)chatMessageCell:(HJChatMessageCell *)cell didClickFoldButton:(UIButton *)button {
    
    if (cell.messageLayout.messageModel.messageType == HJMessageTypeText || cell.messageLayout.messageModel.messageType == HJMessageTypeNotice) {
        
        HJChatMessageTextLayout *textLayout = (HJChatMessageTextLayout *)cell.messageLayout;
        textLayout.isFold = !textLayout.isFold;
        [textLayout calculateLayout];
        [UIView setAnimationsEnabled:NO];
        [self.tableView reloadRowsAtIndexPaths:@[[self.tableView indexPathForCell:cell]] withRowAnimation:UITableViewRowAnimationNone];
        [UIView setAnimationsEnabled:YES];
    }
    
}


- (void)chatMessageDidClickVideoInfoViewCell:(HJChatMessageCell *)cell {
    
    HJChatMessageVideoLayout *videoLayout = (HJChatMessageVideoLayout *)cell.messageLayout;

    HJTaskState state = [videoLayout.messageModel.extension intValue];
    if (state == HJTaskStateSucceed) {
        if ([self.delegate respondsToSelector:@selector(messageController:onSelectMessageContent:)]) {
            [self.delegate messageController:self onSelectMessageContent:cell];
        }
        return;
    }
    
    
    TJWeakify(cell)
    
    if (state == HJTaskStateOngoing) {//取消
        [[HJDownloadManager downloadManager] cancelTaskWithUrl:videoLayout.messageModel.fileUrl completionHandler:^(NSString * _Nonnull url, NSError * _Nonnull error) {
            videoLayout.messageModel.extension = toString(@(HJTaskStateCancel));
            [videoLayout.messageModel bg_saveOrUpdateAsync:nil];
            [videoLayout calculateLayout];
            dispatch_async_main_queue(^{
                weakcell.messageLayout = videoLayout;
            });
        }];
        return;
    }
    
    NSLog(@"state = %ld", state);
 
    
    NSDictionary *dict = videoLayout.messageModel.msg.mj_JSONObject;
    NSInteger fileSize = [dict[@"fileSize"] longLongValue];
    
    NSString *localPath = [HJMessageFileManager videofileFilePathWithSessionId:videoLayout.messageModel.sessionId fileName:videoLayout.messageModel.fileUrl.lastPathComponent];
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPath] && getFileSizeAtPath(localPath) == fileSize) {
        NSLog(@"存在这个路径");
        return;
    }
    

    [[HJDownloadManager downloadManager] downloadTaskWithMessageModel:videoLayout.messageModel destination:localPath progress:^(int64_t completedUnitCount, int64_t totalUnitCount) {
    } completionHandler:nil];
   
}


- (void)chatMessageCellDidClickLinkPreviewView:(HJChatMessageCell *)cell {
    
    HJChatMessageTextLayout *textLayout = (HJChatMessageTextLayout *)cell.messageLayout;
    NSString *url = textLayout.links.firstObject;
    
    HJUIAlertController *alert = [HJUIAlertController alertControllerWithTitle:nil message:url preferredStyle:HJUIAlertControllerStyleActionSheet];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Open link" style:HJUIAlertActionStyleDefault handler:^(HJUIAlertAction * _Nonnull action) {
        [self openLink:url];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Copy link" style:HJUIAlertActionStyleDefault handler:^(HJUIAlertAction * _Nonnull action) {
        [HJTools copyStringToPasteboard:url];
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Add to reading list" style:HJUIAlertActionStyleDefault handler:^(HJUIAlertAction * _Nonnull action) {
        if ([SSReadingList supportsURL:[NSURL URLWithString:url]]) {
            [[SSReadingList defaultReadingList] addReadingListItemWithURL:[NSURL URLWithString:url] title:nil previewText:nil error:nil];
        } else {
            [HJHUD showMessage:@"Unsupported links"];
        }
    }]];
    [alert addAction:[HJUIAlertAction actionWithTitle:@"Cancel" style:HJUIAlertActionStyleCancel handler:^(HJUIAlertAction * _Nonnull action) {
        
    }]];
    [alert showInViewController:self];
    
}

- (void)chatMessageCellDidClickRetryButton:(HJChatMessageCell *)cell {
    if ([self.delegate respondsToSelector:@selector(messageController:didClickRetryButton:)]) {
        [self.delegate messageController:self didClickRetryButton:cell];
    }
}

- (void)chatMessageCell:(HJChatMessageCell *)cell didClickLink:(NSString *)url {
    [self openLink:url];
}

- (void)openLink:(NSString *)url {
    NSLog(@"chatMessageCellurl = %@", url);
    if ([url.URL.path isEqualToString:getNewsShareUrl().URL.path]) {//跳转到咨讯文章详情
        NSDictionary *queryDict = [HJTools parseQueryForURL:url.URL];
        NSString *articleId = toString(queryDict[@"articleId"]);
        if (articleId) {
            HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageNews];
            flutterController.arguments = @{
                @"type": @([queryDict[@"articleType"] intValue]),
                @"id": articleId,
            };
            NSLog(@"flutterController.arguments = %@", flutterController.arguments);
            NSLog(@"queryDict = %@",queryDict);

            [[HJTools currentNavController] pushViewController:flutterController];
        } else {
            HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageBrowser];
            flutterController.arguments = @{
                @"url": url,
            };
            [[HJTools currentNavController] pushViewController:flutterController];
        }
        return;
    }
    
    HJFlutterController *flutterController = [[HJFlutterController alloc] initWithName:HJFlutterPageBrowser];
    flutterController.arguments = @{
        @"url": url,
    };
    [[HJTools currentNavController] pushViewController:flutterController];
}


- (void)setTopMargin:(CGFloat)topMargin {
    _topMargin = topMargin;
    
    self.tableView.contentInset = UIEdgeInsetsMake(topMargin, 0, 10, 0);
}

- (void)clearAllMessge {
    
}

- (void)deleteMessage:(HJChatMessageLayout *)messageLayout {

    dispatch_async_sql_queue(^{
        
        BOOL result = [HJIM.shareIM.messageManager deleteMessageWithMessageModel:messageLayout.messageModel];
        if (result) {
            
            [HJIM.shareIM.conversationManager getConversationBySessionId:self.sessionModel.sessionId completion:^(HJChatSessionModel * _Nonnull sessionModel) {
                [[NSNotificationCenter defaultCenter] postNotificationName:updateConversationNotification object:sessionModel];
            }];
                        
            dispatch_async_main_queue(^{
                @try {
                    NSInteger index = [self.messageLayouts indexOfObject:messageLayout];
                    [self.messageLayouts removeObject:messageLayout];
                    NSInteger totalRow = [self.tableView numberOfRowsInSection:0];
                    [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

                } @catch (NSException *exception) {
                    [self.tableView reloadData];
                } @finally {
                }
            });
        }
        
    });
    
}


- (void)loadMessageData {
    
    self.pageNumber = 1;
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionModel.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
        
        self.pageNumber++;
        
        NSMutableArray *messageLayouts = [self transMsglayoutsFromMessageModels:messages];
        for (NSInteger i = 0; i < messageLayouts.count; i++) {
            HJChatMessageLayout *messageLayout = messageLayouts[i];
            messageLayout.isShowTime = [self isShowTimeWithMessageModel:messageLayout.messageModel];
            [messageLayout calculateLayout];
        }
        
        [self.messageLayouts removeAllObjects];
        [self.messageLayouts addObjectsFromArray:messageLayouts];
        dispatch_async_main_queue(^{
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
                [self.indicatorView stopAnimating];
                self.tableView.tableHeaderView.tj_height = 0.01;
            }
            [self.tableView reloadData];
            [self.tableView layoutIfNeeded];
            [self scrollToBottom:NO];
        });
    }];
}

- (void)loadMoreMessageData {
    
    [HJIM.shareIM.messageManager loadMessageDatasBySessionId:self.sessionModel.sessionId pageSize:self.pageSize pageNumber:self.pageNumber completion:^(NSArray * _Nonnull messages) {
        
        self.pageNumber++;
        
        NSMutableArray *messageLayouts = [self transMsglayoutsFromMessageModels:messages];
        
        __block CGFloat visibleHeight = 0;
        self.msgForDateModel = [self getFirstShowTimeLayout].messageModel;
        for (NSInteger i = messageLayouts.count - 1; i >= 0; i--) {
            HJChatMessageLayout *messageLayout = messageLayouts[i];
            messageLayout.isShowTime = [self isShowTimeWithMessageModel:messageLayout.messageModel];
            [messageLayout calculateLayout];
            visibleHeight += messageLayout.cellHeight;
        }
        
        dispatch_async_main_queue(^{
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, messageLayouts.count)];
            [self.messageLayouts insertObjects:messageLayouts atIndexes:indexSet];
            
            [self.tableView layoutIfNeeded];
            [self.tableView reloadData];
            
            if (messages.count < self.pageSize) {
                self.isLoadAllMessage = YES;
            }
            
            if (self.isLoadAllMessage) {
                HJChatMessageLayout *messageModelLayout = messageLayouts.firstObject;
                messageModelLayout.isShowTime = YES;
                [messageModelLayout calculateLayout];
                [self.indicatorView stopAnimating];
                self.tableView.tableHeaderView = nil;
            }
            
            [self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentOffset.y + visibleHeight, self.tableView.frame.size.width, self.tableView.frame.size.height) animated:NO];
        });
    }];
}

- (NSMutableArray *)transMsglayoutsFromMessageModels:(NSArray *)msssageModels {
    
    NSInteger currentTimestamp = [NSDate date].timestamp;
    NSMutableArray *messageLayouts = [NSMutableArray array];
    NSMutableArray *changeMessages = [NSMutableArray array];
    
    for (NSInteger i = msssageModels.count - 1; i >= 0; i--) {
        HJChatMessageModel *messageModel = msssageModels[i];
        
        if (messageModel.chatType == HJChatTypeGroup ||
            messageModel.chatType == HJChatTypeSingle ||
            messageModel.chatType == HJChatTypeSystem) {
            
            HJChatUserModel *chatModel = [self queryUserInfoByUserId:messageModel.senderId];
            if (chatModel) {
                BOOL isChange = NO;
                if (chatModel.showName && ![messageModel.senderNickname isEqualToString:chatModel.showName]) {
                    messageModel.senderNickname = chatModel.showName;
                    isChange = YES;
                }
                
                if (chatModel.avatar && ![messageModel.senderAvatar isEqualToString:chatModel.avatar]) {
                    messageModel.senderAvatar = chatModel.avatar;
                    isChange = YES;
                }
                
                if (isChange) {
                    [changeMessages addObject:messageModel];
                }
            }
        }
        
        HJChatMessageLayout *messageLayout = [HJChatMessageLayout messagelayoutWithMessageModel:messageModel];
        [messageLayouts addObject:messageLayout];
        
        if (messageLayout.messageModel.msgStatus == HJMessageStatusSending && (currentTimestamp - messageModel.timestamp.integerValue / 1000) > 180) {
            messageLayout.messageModel.msgStatus = HJMessageStatusFail;
            [changeMessages addObject:messageModel];
        }
    }
    
    if (changeMessages.count) {
        [HJChatMessageModel bg_saveOrUpdateArray:changeMessages];
    }
    return messageLayouts;
}

- (BOOL)isShowTimeWithMessageModel:(HJChatMessageModel *)messageModel {
    BOOL isShowTime = (self.msgForDateModel == nil || (labs((messageModel.timestamp.integerValue - self.msgForDateModel.timestamp.integerValue) / 1000) > MaxDateMessageDelay));
    if (isShowTime) {
        self.msgForDateModel = messageModel;
    }
    return isShowTime;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= TMessageController_Header_Height
        && !_isLoadAllMessage) {
        [self loadMoreMessageData];
    }
}

- (NSDictionary *)menuDatas {
    if (!_menuDatas) {
        _menuDatas = @{
            @"forward": @{
                @"imageName": @"icon_forward",
                @"name": @"转发",
                @"buttonId": @1,
            },
            @"delete": @{
                @"imageName": @"icon_delete",
                @"name": @"删除",
                @"buttonId": @2,
            },
            @"backups": @{
                @"imageName": @"icon_imcopy",
                @"name": @"备份",
                @"buttonId": @3,
            },
            @"copy": @{
                @"imageName": @"icon_imcopy",
                @"name": @"复制",
                @"buttonId": @4,
            }
        };
    }
    return _menuDatas;
}

- (void)dealloc {
    
    TJLog(@"%s", __func__);
}

- (HJChatUserModel *)queryUserInfoByUserId:(NSString *)userId {
    HJChatUserModel *chatModel = [self.userInfoPool objectForKey:userId];
    if (chatModel) {
        return chatModel;
    }
    
    chatModel = [HJIM.shareIM.userManager queryUserInfoByUserId:userId];
    if (chatModel) {
        [self.userInfoPool setObject:chatModel forKey:userId];
        return chatModel;
    }
    return nil;
}

- (NSMutableDictionary *)userInfoPool {
    if (!_userInfoPool) {
        _userInfoPool = [NSMutableDictionary dictionary];
    }
    return _userInfoPool;
}

@end
